/**
 * request 封装方法
 */

import Taro from "@tarojs/taro";
import { getBaseUrl } from "./utils";
import interceptors from "./interceptors";

interceptors.forEach((i) => Taro.addInterceptor(i));

class request {
  baseOptions(params, method = "POST") {
    let { funcode, data, load } = params;
    const accessToken = Taro.getStorageSync("accessToken");
    const userId = Taro.getStorageSync("userId");
    const BASE_URL = getBaseUrl();

    const comParam = {
      funcode: "account.access." + funcode,
      mchId: Taro.getStorageSync("mchId"),
    };

    data = !data ? comParam : { ...data, ...comParam };

    if (funcode) {
      if (accessToken) {
        data.accessToken = accessToken;
      } else {
        Taro.redirectTo({ url: "/pages/index" });
        return false;
      }
      data.userId = userId;
    }

    const option = {
      url: BASE_URL,
      data,
      method: method,
      header: {
        "content-type": "application/json",
      },
      mode: "cors",
      timeout: 100000,
    };

    load &&
      Taro.showLoading({
        title: "加载中...",
        mask: true,
      });

    return Taro.request(option);
  }

  get(funcode, data = "") {
    let option = {
      funcode,
      data,
    };
    return this.baseOptions(option);
  }

  post(funcode, data, load = false) {
    let params = {
      funcode,
      data,
      load,
    };
    return this.baseOptions(params, "POST");
  }

  put(url, data = "") {
    let option = {
      url,
      data,
    };
    return this.baseOptions(option, "PUT");
  }

  delete(url, data = "") {
    let option = {
      url,
      data,
    };
    return this.baseOptions(option, "DELETE");
  }
}

export default new request();
